package com.kgc.scd.controller;

import com.alibaba.fastjson.JSON;
import com.kgc.scd.vo.SensitiveWord;
import com.kgc.scd.constant.CommonConstant;
import com.kgc.scd.service.SensitiveWordService;
import com.kgc.scd.util.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Created On : 2022/11/12.
 * <p>
 * Author : zhukang
 * <p>
 * Description: 敏感词测试入口
 */
@Slf4j
@RestController
public class SensitiveWordController {

    @Autowired
    private SensitiveWordFilter sensitiveWordFilter;

    @Autowired
    private SensitiveWordService sensitiveWordService;

    @Autowired
    private RedisUtils redisUtils;

    /**
     * @author : zhukang
     * @date   : 2022/11/12
     * @param  : [java.lang.String]
     * @return : com.kgc.sbt.util.RequestResult<java.lang.String>
     * @description : 测试搜索中的敏感词
     */
    @GetMapping("/testSensitiveWord")
    public RequestResult<String> testSensitiveWord(@RequestParam String searchKey){

        // 校验搜索关键字中，是否包含敏感词，如果包含，提示错误
        if(sensitiveWordFilter.isContainSensitiveWordMin(searchKey)){
            log.warn("------ 命中敏感词，搜索关键字：{} ------", searchKey);
            return ResultBuildUtil.fail("搜索失败，命中敏感词");
        }
        return ResultBuildUtil.success();
    }

    /**
     * @author : zhukang
     * @date   : 2022/11/12
     * @param  : [java.lang.String]
     * @return : com.kgc.sbt.util.RequestResult<java.lang.String>
     * @description : 测试添加敏感词，并将敏感词同步到redis中，也可以作为系统敏感词初始化功能
     */
    @PostMapping("/addSensitiveWord")
    public RequestResult<String> addSensitiveWord(@RequestParam Integer tid, @RequestParam String word){

        // 添加敏感词到数据库
        if(sensitiveWordService.addSensitiveWord(tid,word)){
            // 从数据库查询敏感词，转换为set集合
            Set<String> set = sensitiveWordService.getSensitiveWords().stream().map(SensitiveWord::getWord).collect(Collectors.toSet());

            // 将敏感词库加入到HashMap中，确定有穷自动机DFA
            Map sensitiveWordMap = SensitiveWordUtil.addSensitiveWordToHashMap(set);

            // 存入redis
            redisUtils.set(SensitiveWordUtil.getSensitiveWordKey(null), JSON.toJSONString(sensitiveWordMap));

            // 打开redis中，敏感词开关
            redisUtils.set(CommonConstant.SENSITIVE_WORD_ON_OFF, "on", 3600);

            // 返回成功
            return ResultBuildUtil.success(word);
        }

        // 返回失败
        return ResultBuildUtil.fail();
    }
}
